import React, {Component} from 'react'
import LoginForm from './login_form'
import logo from './images/logo.png'
import {reqLogin} from '../../api'
import storeUtil from '../../util/storeUtil'
import MemorizeUtil from '../../util/memorizeUtil'
import {Redirect} from "react-router-dom";

export default class Login extends Component {

  state={
    errorMsg: '',
  }

  login = async({username,password})=>{
    const result = await reqLogin(username,password)
    /* result
    // 输入正确：
    {
      "status": 0,
      "data": {
          "_id": "5ca6fdbebaacbe09345ce840",
          "username": "admin",
          "password": "21232f297a57a5a743894a0e4a801fc3",
          "create_time": 1554447806315,
          "__v": 0,
          "role": {
              "menus": []
          }
      }
    }
    // 输入有误：
    {
      "status": 1,
      "msg": "用户名或密码不正确!"
    }
    */
    if(result.status === 0){
      const user = result.data
      //store user to LocalStorage
      storeUtil.saveUser(user)
      //memorize user to memory
      MemorizeUtil.user = user
      this.props.history.replace('/')
    }else{
      this.setState({
        errorMsg: result.msg
      })
    }
  }

render(){
    if(MemorizeUtil.user && MemorizeUtil.user._id){
      return <Redirect to='/'/>
    }

    const {errorMsg} = this.state
    return (
      <div className='login'>
        <div className='login-header'>
          <img src={logo} alt='Welcome to China'/>
          UserMangementSystem
        </div>
        <div className='login-content'>
          <div className="login-box">
            <div className='error-msg-wrap'></div>
            <div className='error-msg-wrap'>
              <div className={errorMsg?'show':''}>{errorMsg}</div>
            </div>
            <div className="title">UserLogin</div>
            <LoginForm login={this.login}/>
          </div>
        </div>
      </div>
    )
  }
}